/*
 * Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package com.i360day.invoker;

import com.i360day.invoker.common.HttpInvokerRemoteConstant;
import com.i360day.invoker.exception.HttpInvokerException;
import com.i360day.invoker.http.Request;
import com.i360day.invoker.http.Response;
import com.i360day.invoker.properties.HttpInvokerProperties;
import com.i360day.invoker.request.HttpInvokerRequest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author: liju.z
 * @date: 2024/3/18 13:38
 */
public class RedisHttpInvokerRequest implements HttpInvokerRequest {
    private final RedisConnectionFactory redisConnectionFactory;
    private final String RPC_REPLY_KEY = "amqp.invoker.rpc.reply.%s";
    private final HttpInvokerProperties httpInvokerProperties;

    public RedisHttpInvokerRequest(RedisConnectionFactory redisConnectionFactory, HttpInvokerProperties httpInvokerProperties) {
        this.redisConnectionFactory = redisConnectionFactory;
        this.httpInvokerProperties = httpInvokerProperties;
    }

    @Override
    public Response executor(RequestTemplate requestTemplate) throws IOException {
        Request request = requestTemplate.convertRequest();
        CompletableFuture<byte[]> future = new CompletableFuture<>();

        RedisConnection connection = redisConnectionFactory.getConnection();
        RedisRequest redisRequest = RedisRequest.getRequest(requestTemplate);
        try {
            connection.subscribe((message, pattern) -> future.complete(message.getBody()), redisRequest.getReplyTo().getBytes());
            connection.publish(request.getUri().getPath().getBytes(), HttpInvokerRemoteConstant.objectMapper.writeValueAsBytes(redisRequest));
            byte[] bytes = future.get(httpInvokerProperties.getReadTimeout(), TimeUnit.MILLISECONDS);
            //返回信息
            return Response.Builder.create()
                    .body(new ByteArrayInputStream(bytes))
                    .status(bytes != null ? HttpStatus.OK.value() : HttpStatus.INTERNAL_SERVER_ERROR.value())
                    .setContextType(MediaType.APPLICATION_JSON_VALUE)
                    .request(request)
                    .build();
        } catch (Exception ex) {
//            future.cancel(true);
            throw new HttpInvokerException(ex);
        } finally {
            connection.getSubscription().unsubscribe(redisRequest.getReplyTo().getBytes());
        }
    }
}
